ResourceSystem = System.new()
ResourceSystem.imageDatas = {}
ResourceSystem.images = {}
ResourceSystem.toLoad = {}
ResourceSystem.spriteFrames = {}


function ResourceSystem:hasImage(url)
    return self.images[url] ~= nil
end
function ResourceSystem:_loadImageData(url)
    if self.imageDatas[url] then
        return self.imageDatas[url]
    end
    local data = love.image.newImageData(url)
    self.imageDatas[url] = data
end

function ResourceSystem:loadImage(url)
    if self.images[url] then
        return self.images[url]
    end
    self:_loadImageData(url)
    self.images[url] = love.graphics.newImage(self.imageDatas[url])
    return self.images[url]
end

function ResourceSystem:setImageData(key, imgData)
    self.imageDatas[key] = imgData
end

function ResourceSystem:setImage(key, img)
    self.images[key] = img
end

function ResourceSystem:addLoadTask(task)
    if type(task) == "string" then
        task = {url=task}
    end
    table.insert(self.toLoad, task)
end

function ResourceSystem:update()
    if #self.toLoad == 0 then
        return
    end
    local task = table.remove(self.toLoad, 1)
    if task.url then
        self:loadImage(task.url)
    else
        local canvas = GetTempCanvasN2(task.w, task.h)
        love.graphics.setCanvas(canvas)
        love.graphics.clear(0, 0, 0, 0)
        love.graphics.setBlendMode("alpha")
        love.graphics.setColor(1, 0, 0, .5)
        love.graphics.rectangle("fill", 0,0, 100,100)
        love.graphics.setCanvas()
        self.imageDatas[task.id] = canvas.newImageData()
        self.images[task.id] = love.graphics.newImage(self.imageDatas[task.id])
        if task.cb then
            task.cb()
        end
    end
end

function ResourceSystem:loadSpriteFrame(url)
    if self.spriteFrames[url] then
        return self.spriteFrames[url]
    end
    local image = self:loadImage(url)
    if not image then
        Console.error("loadSpriteFrame is not exsit", url)
    end
    local sp = SpriteFrame.new(image)
    self.spriteFrames[url] = sp
    return sp
end

RegisterSystem(ResourceSystem)